package node;

import lexer.LexType;
import parser.Parser;

import java.io.IOException;
import java.util.List;

public class VarDefNode extends ASTNode {
    public final String name = "<VarDef>";
    // VarDef → Ident [ '[' ConstExp ']' ] | Ident [ '[' ConstExp ']' ] '=' InitVal
    private final String identNode;
    private int lineno;
    private final ConstExpNode constExpNode;
    private InitValNode initValNode;

    public VarDefNode(String identNode, ConstExpNode constExpNode, InitValNode initValNode) {
        this.identNode = identNode;
        this.constExpNode = constExpNode;
        this.initValNode = initValNode;
    }

    public VarDefNode(String identNode, ConstExpNode constExpNode) {
        this.identNode = identNode;
        this.constExpNode = constExpNode;
    }

    @Override
    public void show() throws IOException {
        Parser.parserWriter.write(LexType.IDENFR + " " + identNode + "\n");
        if (constExpNode != null) {
            Parser.parserWriter.write(LexType.LBRACK + " " + "[" + "\n");
            constExpNode.show();
            Parser.parserWriter.write(LexType.RBRACK + " " + "]" + "\n");
        }
        if (initValNode != null) {
            Parser.parserWriter.write(LexType.ASSIGN + " " + "=" + "\n");
            initValNode.show();
        }
        Parser.parserWriter.write(name + "\n");
    }

    public ConstExpNode getConstExpNode() {
        return constExpNode;
    }

    public String getIdentNode() {
        return identNode;
    }

    public int getLineno() {
        return lineno;
    }

    public InitValNode getInitValNode() {
        return initValNode;
    }

    public void setLineno(int lineno) {
        this.lineno = lineno;
    }

    public boolean isArray() {
        return constExpNode != null;
    }

    public List<Integer> calculateArray() {
        if (initValNode != null) {
            return initValNode.calculateArray();
        } else {
            return null;
        }
    }

    public int calculate() {
        if (initValNode != null) {
            return initValNode.calculate();
        } else {
            return 0;
        }
    }

    public String calculateCharArray() {
        if (initValNode != null) {
            return initValNode.calculateCharArray();
        } else {
            return null;
        }
    }

}
